<template>
  <el-card shadow="hover" style="width: 350px">
    <template #header>
      <div class="option-header">
        <div class="option-header-content"><span>触碰期权</span></div>
        <div v-if="props.calcSuccess=='true'" class="option-header-content"><span style="color: #22bb98 ">计算成功</span></div>
        <!--        <div v-if="props.calcSuccess=='false'" class="option-header-content"><span style="color: #e53c3c">计算失败</span></div>-->
        <div v-if="props.calcSuccess=='false'" class="option-header-content">
          <el-tooltip  effect="light"  >
            <template #content> <div style="width: 280px;">
              <span style="color: #e53c3c;">{{props.errorMsg}}</span>
            </div> </template>
            <span style="color: #e53c3c">计算失败</span>
          </el-tooltip>
        </div>
        <div>
          <el-button style="background: transparent;" :disabled="cpoyWait" class="delete" @click="copy" title="复制">
            <el-icon>
              <copy-document/>
            </el-icon>
          </el-button>
          <el-button style="background: transparent;" class="delete" @click="cancel" title="关闭">
            <el-icon>
              <circle-close/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <el-form ref="formRef" :disabled="form.data.readOnly" :model="form.data" label-width="auto" size="small"
             :rules="rules">
      <div class="optionst01">
        <el-form-item label="交易方向" prop="payDirection">
          <el-radio-group v-model="form.data.payDirection" size="small" :fill="getColor()">
            <el-radio-button label="1">买入</el-radio-button>
            <el-radio-button label="-1">卖出</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标的" label-width="auto" prop="instrumentId">
          <Underlyer ref="underlyerIdRef" :filterDate="true" v-model="form.data.instrumentId" @change="onBlurInstrumentId" :underlyerId="form.data.instrumentId"/>
        </el-form-item>
        <!--合约乘数-->
        <!--      todo-->
        <!--涨跌类型-->
        <el-form-item label="涨跌类型" label-width="auto" prop="optionType">
          <el-radio-group v-model="form.data.optionType" size="small">
            <el-radio label="Call">看涨</el-radio>
            <el-radio label="Put">看跌</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="起始日" label-width="auto" prop="effectiveDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.effectiveDate" @blur="onBlurEffectiveDate" type="date" placeholder="">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="期限" label-width="auto" prop="term">
          <Numberinput v-model="form.data.term" append="D"/>
        </el-form-item>

        <el-form-item label-width="auto" label="到期日" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationDate" type="date" placeholder=""/>
        </el-form-item>

        <el-form-item label="到期支付偏移" label-width="auto" prop="paymentDaysOffset">
          <Numberinput v-model="form.data.paymentDaysOffset" append="D"/>

        </el-form-item>

        <el-form-item label-width="auto" label="到期支付日" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationPaymentDate"
                          placeholder="" type="date"/>
        </el-form-item>

        <el-form-item label="名义本金" prop="notional">
          <InputAmount v-model:value="form.data.notional" append="元" precision="2"></InputAmount>
        </el-form-item>


        <el-form-item label="期初价格" label-width="auto">
          <el-col :span="8">
            <el-checkbox name="status" false-label="0" true-label="1" v-model="form.data.priceOnWait">待定</el-checkbox>
          </el-col>
          <el-col :span="16">
            <InputAmount v-model:value="form.data.spotPrice" :disabled="form.data.priceOnWait=='1'" append="元"
                         precision="2"/>
          </el-col>
        </el-form-item>

        <el-form-item label="交易数量" prop="optionEntitlement">
          <Numberinput v-model="form.data.optionEntitlement" precision="2"  :disabled="form.data.priceOnWait=='1'" @change="optionEntitlementChange"/>
        </el-form-item>
        <el-form-item v-show="false" label="参与率" prop="participationRate">
          <Numberinput v-model="form.data.participationRate" precision="2" append="%"/>
        </el-form-item>
      </div>
      <!---------------------------------------------- 分割线---------------------------------------------------------->
      <div class="optionst02">
        <el-form-item label="障碍方向" prop='knockType'>
          <dictCombox v-model="form.data.knockType"
                      :style="{width: '100%'}"
                      dictType="knockType"></dictCombox>
        </el-form-item>

        <el-form-item v-if="form.data.knockType.indexOf('double')==-1" label="障碍价比例" prop='levelPercentage'>
          <Numberinput v-model="form.data.levelPercentage" append="%"/>
        </el-form-item>
        <el-form-item v-if="form.data.knockType.indexOf('double')>-1" label="低障碍价比例" prop='lowLevelPercentage'>
          <Numberinput v-model="form.data.lowLevelPercentage" append="%"/>
        </el-form-item>
        <el-form-item v-if="form.data.knockType.indexOf('double')>-1" label="高障碍价比例" prop='heightLevelPercentage'>
          <Numberinput v-model="form.data.heightLevelPercentage" append="%"/>
        </el-form-item>

        <el-form-item label="触碰支付方式" prop='compensateDay'>
          <dictCombox v-model="form.data.compensateDay"
                      :style="{width: '100%'}"
                      dictType="compensateDay"></dictCombox>
        </el-form-item>

        <el-form-item label="行权收益率" prop='paymentAmountPecentage1'>
          <Numberinput v-model="form.data.paymentAmountPecentage1" :max="1000000" :min="0" append="%"/>
        </el-form-item>

        <el-form-item v-if="form.data.knockType == 'double_knock_in'" label="保底收益率" prop='paymentAmountPecentage2'>
          <Numberinput v-model="form.data.paymentAmountPecentage2" :max="10000000" :min="0" append="%"/>
        </el-form-item>

        <el-form-item label="观察频率" prop='knockObsFreq'>
          <dictCombox v-model="form.data.knockObsFreq" :style="{width: '100%'}"
                      dictType="scheduleType" filterKey="0,1"
                      prop='knockObsFreq'></dictCombox>
        </el-form-item>
        <el-form-item label="是否年化" prop='moneynessOption'>
          <dictCombox v-model="form.data.moneynessOption"
                      dictType="boolType"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>
        <el-form-item v-if="false" label="计息天数">
          <Numberinput v-model="form.data.term" append="D"/>
        </el-form-item>

        <el-form-item v-if="form.data.moneynessOption ==1" label="计息基准" prop='daycounter'>
          <dictCombox v-model="form.data.daycounter"
                      dictType="dayCounter"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>


        <el-form-item class="operation">
          <el-button type="primary" @click="calc">计算</el-button>
          <el-button @click="save2CalcLog" v-show="props.useType=='calc'" :disabled="form.data.priceOnWait=='1'">存为草稿</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="optionst03">
      <PricingParam ref="PricingParamRef" :formData="form.data"  :valueDate="props.valueDate"  :index="props.index" label-width="auto" :productType="productType"
                    :disabled="form.data.readOnly" size="small"
                    :calcPricingParam="props.calcPricingParam"></PricingParam>
    </div>
    <singleResult :result="form.result" :index="props.index"></singleResult>
  </el-card>
</template>

<script setup>
import {getCurrentInstance, onMounted, onUpdated, provide, reactive, ref, toRefs, watch, nextTick} from 'vue'
import Underlyer from '@/xquant/base/underlyer'
import Numberinput from '@/xquant/base/number'
import InputAmount from '@/xquant/base/InputAmount'
import dictCombox from '@/xquant/base/dictCombox'
import PricingParam from '@/views/calc/otcOtion/pricingparam/index'
import singleResult from '@/views/calc/otcOtion/result/single'
import {getTradeDay} from '@/utils/calc'
import {isVoid, isNotVoid, calcAnnualizedByTerminationPaymentDate} from '@/utils/util'
import {getTerminationPaymentDate, getOffset} from '@/api/calc/otcOption/calc'
import {debounce} from 'lodash'
import {setCommonSpotPrice} from '@/views/calc/otcOtion/instrument/common/common'
import {formartFormP4, formartTableP2, unFormartNumber, formartFormP2, numberPrecision} from '@/utils/numberUtil'
import {validateDates} from "./common/validate";

const getColor = () => {
  return form.data.payDirection == '1' ? '#E53C3C' : '#22BB98'
}
 const {proxy} = getCurrentInstance()
const productType = ref('Touch')
const cpoyWait = ref(false)
const labelWidth = ref('111px')
const form = reactive({
  data: {
    payDirection: '1',
    instrumentId: null,
    readOnly: false,
    optionType: 'Call',
    effectiveDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    terminationDate: '',
    terminationPaymentDate: '',
    term: 30,
    paymentDaysOffset: '0',
    priceOnWait: '0',
    spotPrice: '',
    strike: 0,
    notional: '',
    optionEntitlement: '',
    knockType: 'up_and_in',
    participationRate: 100,
    calendar: 'CHINA_EX',
    exerciseType: 'European',

    levelPercentage: '',
    lowLevelPercentage: '',
    heightLevelPercentage: '',
    compensateDay: '',
    strikePercentage: 100,
    moneynessOption: '1',
    paymentAmountPecentage1: '',
    paymentAmountPecentage2: '',
    moneynessOption2: ['1'],
    knockObsFreq: '',
    daycounter: 'Actual/365',

  },
  result: {},
  initFlag:''
})

const save2CalcLog = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) props.save2CalcLog(res, props.index)
  })

}

const rules = {
  payDirection: [{required: true, message: '请选择交易方向', trigger: 'change'}],
  instrumentId: [{required: true, message: ' ', trigger: 'change'}],
  optionType: [{required: true, message: '请选择涨跌类型', trigger: 'change'}],
  effectiveDate: [{required: true, message: ' ', trigger: 'change'}],
  terminationDate: [{required: true, message: ' ', trigger: 'change'}],
  term: [{required: true, message: ' ', trigger: 'change'}],
  paymentDaysOffset: [{required: true, message: ' ', trigger: 'change'}],
  notional: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  daycounter: [{required: true, message: ' ', trigger: 'change'}],
  daycounterTerm: [{required: true, message: ' ', trigger: 'change'}],
  knockType: [{required: true, message: ' ', trigger: 'change'}],
  spotPrice: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  optionEntitlement: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strike: [{required: true, message: ' ', trigger: 'change'}],
  strikePercentage: [{required: true, message: ' ', trigger: 'change'}],
  participationRate: [{required: true, message: ' ', trigger: 'change'}],
  levelPercentage: [{required: true, message: ' ', trigger: 'change'}],
  lowLevelPercentage: [{required: true, message: ' ', trigger: 'change'}],
  heightLevelPercentage: [{required: true, message: ' ', trigger: 'change'}],
  compensateDay: [{required: true, message: ' ', trigger: 'change'}],
  moneynessOption: [{required: true, message: ' ', trigger: 'change'}],
  knockObsFreq: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmountPecentage1: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmountPecentage2: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmount: [{required: true, message: ' ', trigger: 'change'}],
}

watch(() => props.result, (nv, ov) => {
  let other = {
    'type': '触碰',
    '标的': computed(() => {
      if (proxy.$refs.underlyerIdRef&&proxy.$refs.underlyerIdRef.underlyerIdsList[0]) {
        return (proxy.$refs.underlyerIdRef.underlyerIdsList[0].productName+'').trim().split(' ').join(',')
      }
    }),
    '交易日期': props.valueDate,
    '合约类型': form.data.optionType == 'Call' ? 'C' : 'P',
    '合约交易方向': form.data.payDirection == '1' ? '客户卖价' :  '客户买价',
    '到期支付日': form.data.terminationDate,
    '数量': formartFormP2(form.data.optionEntitlement),
    '名义金额': formartFormP2(form.data.notional),
    '开仓标的价': formartFormP2(form.data.spotPrice),
    '期权单价': computed(() => {
      if (nv) {
        return formartFormP2(nv.npv / form.data.optionEntitlement)
      }
    }),
    '百分比估值': computed(() => {
      if (nv) {
        return formartFormP2(100 * nv.npv / form.data.notional)
      }
    }),
  }
  form.result = Object.assign(other, nv)
}, {immediate: true})
watch(() => form.data.priceOnWait, (nv, ov) => {
  if (nv == '1') {
    form.data.spotPrice = 0
  } else {
    setSpotPrice()
  }
})
watch(() => form.data.paymentDaysOffset, (nv, ov) => {
  if (nv == '') return
  onpaymentDaysOffsetChange()
})
const onpaymentDaysOffsetChange = debounce(function () {
  getTerminationPaymentDate({
    'calDay': form.data.terminationDate,
    'offset': form.data.paymentDaysOffset
  }).then(response => {
    if (response.errorCode != 0) {

    } else {
      form.data.terminationPaymentDate = response.result.CAL_DAY

    }
  })
}, 1000)
watch(() => form.data.terminationPaymentDate, (nv, ov) => {
  if (nv == ov || nv == '') return
  onterminationPaymentDate()
})
const onterminationPaymentDate = debounce(function (nv, ov) {
  getOffset({
    'day': form.data.terminationPaymentDate,
    'calDay': form.data.terminationDate
  }).then(response => {
    if (response.errorCode != 0) {

    } else {
      if (response.result == null) {
        onpaymentDaysOffsetChange()
        return
      }
      form.data.paymentDaysOffset = response.result.i
    }
  })
}, 1000)
onUnmounted(() => {
  // 移除组件时，取消定时器
  onpaymentDaysOffsetChange.cancel()
  onterminationPaymentDate.cancel()
})
const onBlurTerminationDate= (nv, ov) => {
  let a = proxy.$moment(form.data.terminationDate)
  let b = proxy.$moment(form.data.terminationPaymentDate)
  form.data.paymentDaysOffset = b.diff(a, 'days')
}
watch(() => [form.data.effectiveDate, form.data.terminationDate], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {
    let a = proxy.$moment(n2v)
    let b = proxy.$moment(nv)
    form.data.term = a.diff(b, 'days')
  }
})
watch(() => [form.data.term], ([newValue], [oldValue]) => {
  if (isNotVoid(String(form.data.effectiveDate)) && isNotVoid(String(newValue))) {
    let a = proxy.$moment(form.data.effectiveDate)
    form.data.terminationDate = a.add(newValue, 'days').format('YYYY-MM-DD')
    onpaymentDaysOffsetChange()
  }
})
watch(() => [form.data.notional, form.data.spotPrice], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {

    form.data.optionEntitlement = String(Number(nv) / Number(n2v))
  }
})

watch(() => [form.data.notional], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(newValue, form.data.spotPrice, form.data.optionEntitlement)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.optionEntitlement = proxy.lsh.round(proxy.lsh.divide(newValue, form.data.spotPrice), 4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.spotPrice = proxy.lsh.round(proxy.lsh.divide(newValue, form.data.optionEntitlement), 4)
      return
    }
  }
})
watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(form.data.notional, newValue, form.data.optionEntitlement)) {
    return
  }

  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.notional))) {
      form.data.optionEntitlement = proxy.lsh.round(proxy.lsh.divide(form.data.notional, newValue), 4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.notional = proxy.lsh.round(proxy.lsh.multiply(form.data.optionEntitlement, newValue), 4)
      return
    }
  }
})
/**
 * 获取标的价格
 * */
const setSpotPrice = () => {
  setCommonSpotPrice(proxy,form,props)
}
const optionEntitlementChange = (newValue) => {
  if (form.data.priceOnWait == '1') return
  if (optionEntitlementLinkValid(form.data.notional, form.data.spotPrice, newValue)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.notional = proxy.lsh.round(proxy.lsh.multiply(newValue, form.data.spotPrice), 0)
      return
    }
    if (isNotVoid(String(form.data.notional))) {
      form.data.spotPrice = proxy.lsh.round(proxy.lsh.divide(form.data.notional, newValue), 4)
      return
    }
  }
}

function optionEntitlementLinkValid(notional, spotPrice, optionEntitlement) {
  if (isNotVoid(String(notional)) && isNotVoid((String(spotPrice))) && isNotVoid(String(optionEntitlement))) {
    if (proxy.lsh.isEqual(proxy.lsh.round(proxy.lsh.toNumber(optionEntitlement.strike), 4), proxy.lsh.round(proxy.lsh.divide(notional, spotPrice), 4))) {
      return true
    } else {
      return false
    }
  }
}


watch(() => [form.data.knockType], ([newValue], [oldValue]) => {
  switch (form.data.knockType) {
    case 'double_knock_in':
      rules.levelPercentage[0].required = false
      rules.lowLevelPercentage[0].required = true
      rules.heightLevelPercentage[0].required = true
      rules.paymentAmountPecentage1[0].required = true
      rules.paymentAmountPecentage2[0].required = true
    case 'double_knock_out':
      rules.levelPercentage[0].required = false
      rules.lowLevelPercentage[0].required = true
      rules.heightLevelPercentage[0].required = true
      rules.paymentAmountPecentage1[0].required = true
      rules.paymentAmountPecentage2[0].required = false
    case 'down_and_out':
    case 'down_and_in':
    case 'up_and_in':
    case 'up_and_out':
      URL = 'asd'
      break
    default:

      break
  }
  if (isNotVoid(form.data.knockType)) {
    if (form.data.knockType == 'double_knock_in') {

    } else if (form.data.knockType == 'double_knock_in') {

    } else if (form.data.knockType == 'double_knock_in') {

    } else if (form.data.knockType == 'double_knock_in') {

    }
  }
})


watch(() => [props.cfgId,form.data.instrumentId], ([newId, oldId]) => {
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
})

const onBlurInstrumentId = () => {
  setSpotPrice()
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
}
watch(() => props.valueDate, (newValue, oldValue) => {
  if (newValue != oldValue) {
    setSpotPrice()
    //触发修改定价参数的价格
    proxy.$refs.PricingParamRef.setSpotPrice({
      valueDate:props.valueDate,
      instrumentId:form.data.instrumentId
    })
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})
const onBlurEffectiveDate = () => {
  form.initFlag = false
  setSpotPrice()
}

watch(() => form.data.exerciseType, (nv, ov) => {
  if (form.data.exerciseType == 'American') {
    form.data.startDate = form.data.effectiveDate
    form.data.endDate = form.data.terminationDate
  }
}, {
  immediate: true
})
const props = defineProps({
  /*是否为重放*/
  isReCalc: {
    type: Boolean,
    default: false
  },
  calcSuccess:{
    type: String,
    default: ''
  },
  errorMsg:{
    type: String,
    default: ''
  },
  save2CalcLog: {type: Function, default: null},
  index: {
    type: String,
    default: ''
  },
  del: {
    type: Function,
    default: null
  },
  copy: {
    type: Function,
    default: null
  },
  calc: {
    type: Function,
    default: null
  },
  getDefaultCfg: {
    type: Function,
    default: null
  },
  calcPricingParam: {
    type: Object,
    default: {}
  },
  result: {
    type: Object,
    default: {}
  },
  setformData: {
    type: Function,
    default: null
  },
  formData: {
    type: Object,
    default: null
  },
  cfgId: {type: String, default: ''},
  valueDate: {type: String, default: ''}
})
const getResult = () => {
  var data = []
  for (var item in props.result) {
    if (['npv', 'delta', 'gamma', 'vega', 'theta', 'rho', 'spotPrice', 'dscRate'].includes(item)) {
      data.push({
        key: item,
        val: proxy.lsh.ceil(props.result[item], 4)
      })
    }
  }
  return data
}
//定价参数
const getPricingCfg = async () => {
  let query = {
    'calcPricingParam': {
      'cfgId': props.cfgId
    },
    'instrument': {
      'productType': productType.value,
      'termsheet': {
        'underlyerIds': [form.data.instrumentId],
        'customLegs': [{
          'legId': 'leg01',
          'productType': productType.value
        }
        ],
        'legs': [{
          'legId': 'leg01',
          'payDirection': '1'
        }
        ]
      }
    }
  }
  //设置定价参数中的定盘价
  proxy.$refs.PricingParamRef.setSpotPrice({
    valueDate:props.valueDate,
    instrumentId:form.data.instrumentId
  })
  if (props.getDefaultCfg != null) {
    props.getDefaultCfg(query, props.index)
  }
}
const cancel = () => {
  props.del(props.index)
}
const copy = () => {
  props.copy(props.index)
  cpoyWait.value = true;
  setTimeout(() => {
    cpoyWait.value = false;
  }, 1000);
}
const calc = (flag) => {
  /*flag 标识 为All时单次计算不会提示成功或失败*/
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      validateDates(form)
      let calcPriceParam = getCalcPriceParam()

      var observeDates = {
        startDate: form.data.effectiveDate,
        startDateConv: 'Following',
        isIncludeStartDate: '1',
        endDate: form.data.terminationDate,
        endDateConv: 'Following',
        isIncludeEndDate: '1',
        calendar: form.data.calendar,
        frequency: form.data.knockObsFreq == '1' ? '1D' : ''
      }
      var touchs = []
      var touch = {}
      if (form.data.knockType.indexOf('double') > -1) {
        if (form.data.knockType == 'double_knock_in') {
          productType.value = 'DoubleOneTouch'
        } else if (form.data.knockType == 'double_knock_out') {
          productType.value = 'DoubleNoTouch'
        }
        //低障碍条款
        var triggerLow = {
          'type': 'EqualOrLess',
        }
        triggerLow.levelPercentage = proxy.lsh.round(proxy.lsh.divide(form.data.lowLevelPercentage, 100), 4)
        var touchLow = {
          'trigger': triggerLow,
          'observeDates': observeDates
        }
        if (form.data.knockType == 'double_knock_in') {

        } else if (form.data.knockType == 'double_knock_out') {

        }
        touchLow.paymentAmountPecentage = proxy.lsh.round(proxy.lsh.divide(form.data.paymentAmountPecentage, 100), 4)
        touchLow.paymentDateOffset = '1D'
        touchLow.payStyle = form.data.compensateDay
        touchLow.participationRate = proxy.lsh.round(proxy.lsh.divide(form.data.participationRate, 100), 4)
        touchLow.paymentDateConv = 'Following'
        touchLow.paymentDateCalendar = 'CHINA_EX'
        touchs.push(touchLow)
        //高障碍条款
        var triggerHeight = {
          'type': 'EqualOrGreater',
        }
        triggerHeight.levelPercentage = proxy.lsh.round(proxy.lsh.divide(form.data.heightLevelPercentage, 100), 4)
        var touchHeight = {
          'trigger': triggerHeight,
          'observeDates': observeDates
        }
        touchHeight.paymentAmountPecentage = proxy.lsh.round(proxy.lsh.divide(form.data.paymentAmountPecentage, 100), 4)
        touchHeight.paymentDateOffset = '1D'
        touchHeight.payStyle = form.data.compensateDay
        touchHeight.participationRate = proxy.lsh.round(proxy.lsh.divide(form.data.participationRate, 100), 4)
        touchHeight.paymentDateConv = 'Following'
        touchHeight.paymentDateCalendar = 'CHINA_EX'
        touchs.push(touchHeight)

      } else {

        var trigger = {
          'type': 'EqualOrLess',
        }
        trigger.levelPercentage = proxy.lsh.round(proxy.lsh.divide(form.data.levelPercentage, 100), 4)
        productType.value = 'NoTouch'
        if (form.data.knockType == 'down_and_out') {
          trigger.type = 'Less'
        } else if (form.data.knockType == 'up_and_out') {
          trigger.type = 'Greater'
        } else if (form.data.knockType == 'down_and_in') {
          trigger.type = 'EqualOrLess'
          productType.value = 'OneTouch'

        } else if (form.data.knockType == 'up_and_in') {
          trigger.type = 'EqualOrGreater'
          productType.value = 'OneTouch'
        }
        touch.trigger = trigger
        touch.observeDates = observeDates
        touch.paymentAmountPecentage = proxy.lsh.round(proxy.lsh.divide(form.data.paymentAmountPecentage, 100), 4)
        touch.paymentDateOffset = '0D'
        touch.payStyle = form.data.compensateDay
        touch.participationRate = proxy.lsh.round(proxy.lsh.divide(form.data.participationRate, 100), 4)
        touch.paymentDateConv = 'Following'
        touch.paymentDateCalendar = 'CHINA_EX'

      }
      let otcOption = {
        instrument: {
          'termsheet': {
            'notional': form.data.notional,
            'notionalCurrency': 'CNY',
            'settlementType': 'C',
            'settlementCurrency': 'CNY',
            'effectiveDate': form.data.effectiveDate,
            'effectiveDateConv': 'Following',
            'terminationDate': form.data.terminationDate,
            'terminationDateConv': 'Following',
            'terminationDateCalendar': form.data.calendar,
            'underlyerIds': [
              form.data.instrumentId
            ],
            'calendars': [
              form.data.calendar
            ],
            'legs': [
              {
                'legId': 'leg01',
                'payDirection': form.data.payDirection
              }
            ],
            'customLegs': [
              {
                'payDirection': form.data.payDirection,
                periodOfAccrualInterestAdjust: '0',
                'participationRate': String(form.data.participationRate / 100),
                'productType': productType.value,
                'touchs': touchs,
                'touch': touch,
                'exercise': {
                  'type': 'European',
                  'dates': [
                    form.data.terminationDate,
                  ],
                  'conv': 'Following',
                  'calendar': 'CHINA_EX'
                },
                'paymentDateCalendar': 'CHINA_EX',
                'underlyers': [
                  {
                    'instrumentId': form.data.instrumentId,
                    'quoteType': '',
                    'spotPrice': form.data.spotPrice,
                    'basketWeight': '1',
                    'fixingDate': '',
                    'fixingDateConv': 'Preceding',
                    'fixingDateCalendar': form.data.calendar
                  }
                ],
                'numberOfOptions': '1',
                'optionEntitlement': form.data.optionEntitlement,
                'moneynessOption': form.data.moneynessOption,
                'daycounter': form.data.moneynessOption == 1 ? form.data.daycounter : '',
                'fixingRounding': '-1',
                'settlementDateConv': 'Following',
                'settlementDateCalendar': form.data.calendar,
                'settlementDateOffset': form.data.paymentDaysOffset + 'D',
                'legId': 'leg01'
              }
            ],
            'term': form.data.term,
          },
          'productType': productType.value
        },
        calcPricingParam: {
          valueDate: props.valueDate,
          cfgId: props.cfgId,
          calcPPCode: calcPriceParam.calcPPCode,
          underlyingPricingParams: [
            {
              underlyingID: form.data.instrumentId,
              dividend: calcPriceParam.dividend,
              volSurface: calcPriceParam.volSurface,
              funding: calcPriceParam.discount,
              spotPrice: calcPriceParam.spotPrice == '0' ? '' : calcPriceParam.spotPrice,
              spotQuoteType: calcPriceParam.spotQuoteType
            }
          ],
          discount: calcPriceParam.discount,
          'customPricingParam': {}
        },
        underlyingMarkets: [
          {
            'underlyingID': form.data.instrumentId,
            'fixingPrices': [],
            'observerPrices': []
          }
        ]
      }
      if (touchs.length > 0) {
        delete otcOption.instrument.termsheet.customLegs[0][touch]
      } else {
        delete otcOption.instrument.termsheet.customLegs[0][touchs]
      }
      props.calc(otcOption, props.index, flag)
    }
  })
}
const getCalcPriceParam = () => {
  let calcPriceParam = proxy.$refs.PricingParamRef.getCalcPricingParam()
  return calcPriceParam
}
const getFormData = () => {
  return form
}

defineExpose({
  calc, getPricingCfg, getCalcPriceParam, getFormData,proxy
})
onMounted(() => {
  /*获取默认定价配置*/
  // getPricingCfg()
  /*获取预填表单*/
  form.initFlag = props.isReCalc
  if (props.formData != null) {
    form.initFlag = isNotVoid(props.calcPricingParam)
    let data = props.formData.data || props.formData
    form.data = Object.assign(form.data, data)
  }
  // 这里获取DOM的value是旧值
  nextTick(()=>{
    form.initFlag = false
  })
})
watch(() => proxy.$attrs.disabled, (nv) => {
  form.data.readOnly = nv
}, {
  immediate: true
})
watch(()=>form,()=>{

  proxy.$attrs.cacheFormData()
},{deep:true})
</script>
<style>

</style>

